package com.changhai.diabetes.action;

import org.apache.commons.lang.StringUtils;

import com.changhai.diabetes.model.SessionUser;
import com.changhai.diabetes.model.User;
import com.changhai.diabetes.service.CommonService;
import com.changhai.diabetes.util.Constants;
import com.opensymphony.xwork2.ActionContext;

/**
 * 用户登录与退出
 * 
 * @author Andy
 * 
 */
public class AuthAction extends BaseAction {
	private static final long serialVersionUID = 8506686288744262867L;
	private String name; // 用户名
	private String passwd; // 密码
	private String error; // 错误信息
	private CommonService commonService;

	/**
	 * 用户登录,判断用户名密码是否存在
	 */
	@Override
	public String execute() throws Exception {
		if (this.getMethod().equals("logout")) {
			return logout();
		}
		SessionUser sUser = (SessionUser) ActionContext.getContext().getSession().get(Constants.SESSION_USER_KEY);
		if (sUser == null || StringUtils.isBlank(sUser.getLoginName())) {
			if (StringUtils.isBlank(name) || StringUtils.isBlank(passwd)) {		 
				this.error = "用户名密码错误！";
				return ERROR;
			}
			User u = commonService.auth(Constants.DS_CHANGHAI, name, passwd);
			if (u != null && u.getUserid() != null) {
				sUser = new SessionUser(Long.valueOf(u.getUserid()), u.getUsername(), u.getAdmintype());
				ActionContext.getContext().getSession().put(Constants.SESSION_USER_KEY, sUser);
				ActionContext.getContext().getSession().put("user", u);	
				this.setMethod("login");
			} else {
				this.error = "用户名密码错误！";
				return ERROR;
			}
		}

		return "success";
	}

	/**
	 * 用户退出
	 * 
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		ActionContext.getContext().getSession().remove(Constants.SESSION_USER_KEY);
		return "login";
	}

	public String getName() {
		return name;
	}

	public String getPasswd() {
		return passwd;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
}
